/*
 * http.c
 *
 * Copyright (C) 2011 - Dr.NP
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * @version http.c 1.0.0
 * @package libbspehttp
 * @author Dr.NP <np@bsgroup.org>
 * @update 05/17/2011
 */

/**
 * HTTP protocol operator
 *
 * === CHANGELOG ===
 * [05/17/2011] - Creation
 */

#include "bsp.h"

#include "bsp_utils.h"
#include "http.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <err.h>
#include <sys/types.h>

struct http_request_t **free_request_list;
size_t free_request_list_size;
int free_request_total;
struct http_response_t **free_response_list;
size_t free_response_list_size;
int free_response_total;

void http_fill_request(struct http_request_t *, char *, char *);

int http_init()
{
    free_request_list = ensure_list_space(NULL, sizeof(struct http_request_t *), &free_request_list_size, FREE_REQUEST_LIST_INITIAL);
    free_response_list = ensure_list_space(NULL, sizeof(struct http_response_t *), &free_response_list_size, FREE_REQUEST_LIST_INITIAL);

    if (!free_request_list || !free_response_list)
    {
        err(RTN_ERROR_MEMORY_ALLOC, "HTTP request / response list error!!!");
    }

    free_request_total = free_response_total = 0;

    return RTN_SUCCESS;
}

struct http_request_t * http_parse_request(char *input, size_t len)
{
    struct http_request_t *r = NULL;
    char *tmp[4] = {"", "", "", ""}, c, in_space = 0, in_crlf = 0;
    int curr = 0, seg = 0;
    
    //pthread_mutex_lock(&http_list_lock);
    if (free_request_total > 0)
    {
        r = free_request_list[-- free_request_total];
    }

    else
    {
        r = malloc(sizeof(struct http_request_t));
    }

    //pthread_mutex_unlock(&http_list_lock);

    memset(r, 0, sizeof(struct http_request_t));

    // First line of HTTP request is special
    tmp[seg] = input;
    for (curr = 0; curr < len; curr ++)
    {
        c = input[curr];

        if (c == 10 || c == 13 || c == 0)
        {
            // CRLF, break out the first line
            in_space = 1;
            input[curr] = 0;
            break;
        }

        if (c <= 32)
        {
            // Space
            input[curr] = 0;
            if (!in_space)
            {
                if (seg >= 3)
                {
                    break;
                }

                seg ++;
                in_space = 1;
            }
        }

        else
        {
            if (in_space)
            {
                // Next token
                tmp[seg] = input + curr;
                in_space = 0;
            }
        }
    }

    r->method = tmp[0];
    r->request_uri = tmp[1];
    r->version = tmp[2];

    seg = in_space = in_crlf = 0;
    // Variables
    for (; curr < len; curr ++)
    {
        c = input[curr];

        if (c == 10 || c == 13 || c == 0)
        {
            input[curr] = 0;
            // One line
            if (seg == 1)
            {
                http_fill_request(r, tmp[0], tmp[1]);
            }
            
            seg = 0;
            in_space = 1;
            continue;
        }

        if (c <= 32 || c == ':')
        {
            input[curr] = 0;
            
            if (!in_space && seg == 0)
            {
                in_space = 1;
                seg ++;
            }
        }

        else
        {
            if (in_space)
            {
                tmp[seg] = input + curr;
                in_space = 0;
            }
        }
    }
    
    return r;
}

void http_fill_request(struct http_request_t *r, char *key, char *value)
{
    if (!r)
    {
        return;
    }
    
    if (strcasecmp(key, "Cache-Control") == 0)
    {
        r->cache = value;
    }

    else if (strcasecmp(key, "Connection") == 0)
    {
        r->connection = value;
    }

    else if (strcasecmp(key, "Date") == 0)
    {
        r->date = value;
    }

    else if (strcasecmp(key, "Pragma") == 0)
    {
        r->pragma = value;
    }

    else if (strcasecmp(key, "Range") == 0)
    {
        r->range = value;
    }

    else if (strcasecmp(key, "Host") == 0)
    {
        r->host = value;
    }

    else if (strcasecmp(key, "Referer") == 0)
    {
        r->referer = value;
    }

    else if (strcasecmp(key, "User-Agent") == 0)
    {
        r->user_agent = value;
    }

    else if (strcasecmp(key, "Accept") == 0)
    {
        r->accept = value;
    }

    else if (strcasecmp(key, "Accept-Charset") == 0)
    {
        r->accept_charset = value;
    }

    else if (strcasecmp(key, "Accept-Encoding") == 0)
    {
        r->accept_encoding = value;
    }

    else if (strcasecmp(key, "Accept-Language") == 0)
    {
        r->accept_language = value;
    }

    else if (strcasecmp(key, "Authorization") == 0)
    {
        r->authorization = value;
    }

    else if (strcasecmp(key, "Cookie") == 0)
    {
        r->cookie = value;
    }

    else
    {
        // Other stuff
    }
    
    return;
}

struct http_response_t * http_new_response(short status)
{
    struct http_response_t *r = NULL;
    
    //pthread_mutex_lock(&http_list_lock);

    if (free_response_total > 0)
    {
        r = free_response_list[-- free_response_total];
    }

    else
    {
        r = malloc(sizeof(struct http_response_t));
    }

    //pthread_mutex_unlock(&http_list_lock);

    memset(r, 0, sizeof(struct http_response_t));
    r->http_status = status;

    return r;
}

int http_flush_response(struct http_response_t *r)
{
    const int s = 32767;
    int t = 0;
    time_t tm;
    
    if (!r)
    {
        return 0;
    }

    time(&tm);

    if (!r->version || !strlen(r->version))
    {
        r->version = "HTTP/1.1";
    }

    if (!r->content_type || !strlen(r->content_type))
    {
        r->content_type = "text/html";
    }

    t = snprintf(r->original, s, "%s %d OK\n", r->version, r->http_status);
    t += snprintf(r->original + t, s - t, "Server: %s\n", SERVER_ID);
    t += snprintf(r->original + t, s - t, "Date: %s", ctime(&tm));
    t += snprintf(r->original + t, s - t, "Content-Type: %s\n", r->content_type);
    t += snprintf(r->original + t, s - t, "Content-Length: %d\n", r->content_length);

    t += snprintf(r->original + t, s - t, "\n");

    return t;
}

const char * http_mime_type(const char *filename)
{
    char *dot;
    int i;

    dot = strrchr(filename, '.');

    const struct
    {
        const char *suffix;
        const char *mime_type;
    } types[] = 
    {
        {"txt", "text/plain"}, 
        {"c", "text/plain"}, 
        {"cpp", "text/plain"}, 
        {"h", "text/plain"}, 
        {"hpp", "text/plain"},
        {"as", "text/plain"}, 
        
        {"css", "text/css"}, 
        {"js", "text/javascript"},
        {"xml", "text/xml"}, 
        {"htm", "text/html"}, 
        {"html", "text/html"}, 
        {"shtml", "text/html"}, 
        {"hts", "text/html"}, 

        {"gif", "image/gif"}, 
        {"png", "image/png"}, 
        {"bmp", "application/x-ms-bmp"}, 
        {"jpg", "image/jpeg"}, 
        {"jpeg", "image/jpeg"}, 
        {"jpe", "image/jpeg"}, 

        {"wav", "audio/wav"}, 
        {"midi", "audio/midi"}, 
        {"mid", "audio/midi"}, 
        {"mp3", "audio/mpeg"}, 
        {"mp2", "audio/mpeg"}, 
        {"avi", "video/x-msvideo"}, 
        {"mov", "video/quicktime"}, 

        {"pdf", "application/pdf"}, 
        {"rtf", "application/rtf"}, 
        {"doc", "application/msword"}, 
        {"xls", "application/msexcel"}, 
        {"ppt", "application/mspowerpoint"}, 
        {"swf", "application/x-shockwave-flash"}, 

        {"zip", "application/zip"}, 
        {"rar", "application/x-rar-compressed"}, 
        {"gz", "application/x-gzip"}, 
        {"jar", "application/java-archive"}, 
        {"tgz", "application/x-tar"}, 
        {"tar", "application/x-tar"}
    };

    for (i = 0; dot && i < 38; i ++)
    {
        if (0 == strcasecmp(dot + 1, types[i].suffix))
        {
            return types[i].mime_type;
        }
    }
    
    return "application/octet-stream";
}

void http_free_request(struct http_request_t *rq)
{
    struct http_request_t **tmp;
    
    if (!rq)
    {
        return;
    }

    memset(rq, 0, sizeof(struct http_request_t));
    while (free_request_total >= free_request_list_size)
    {
        // Enlarge
        tmp = realloc(free_request_list, sizeof(struct http_request_t *) * free_request_list_size * 2);
        if (tmp)
        {
            free_request_list = tmp;
            free_request_list_size *= 2;
        }
    }
    
    free_request_list[free_request_total ++] = rq;
    
    return;
}

void http_free_response(struct http_response_t *rp)
{
    struct http_response_t **tmp;

    if (!rp)
    {
        return;
    }

    memset(rp, 0, sizeof(struct http_response_t));
    while (free_response_total >= free_response_list_size)
    {
        // Enlarge
        tmp = realloc(free_response_list, sizeof(struct http_response_t *) * free_response_list_size * 2);
        if (tmp)
        {
            free_response_list = tmp;
            free_response_list_size *= 2;
        }
    }

    free_response_list[free_response_total ++] = rp;
    
    return;
}
